package com.yjt.javatest.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjt.javatest.dao.CategoryMapper;
import com.yjt.javatest.dao.QuestionMapper;
import com.yjt.javatest.dao.QuestionTestMapper;
import com.yjt.javatest.entity.Category;
import com.yjt.javatest.entity.Question;
import com.yjt.javatest.entity.QuestionTest;
import com.yjt.javatest.service.QuestionService;
import com.yjt.javatest.service.TestService;
import com.yjt.javatest.utils.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

@Service
public class QuestionServiceImpl extends ServiceImpl<QuestionMapper, Question> implements QuestionService {


    @Resource
    QuestionMapper questionMapper;
    @Resource
    QuestionTestMapper questionTestMapper;
    @Resource
    TestService testService;
    @Resource
    CategoryMapper categoryMapper;



    //锁



    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRES_NEW)
    @Override
    public APIResponse deleteQuestion(Integer questionId) {
        try{
            Question question = questionMapper.selectById(questionId);
            if(Objects.isNull(question)) {
                return APIResponse.error("无该题目!");
            }
            SecurityUtil.checkUserAuthority(question.getUserId());
            //删除问题测试表中数据
            questionTestMapper.deleteByQuestionId(Long.valueOf(questionId));
            //删除该问题
            questionMapper.deleteById(Long.valueOf(questionId));
            return APIResponse.success("删除成功");
        }catch (Exception e){
            e.printStackTrace();
            return APIResponse.error(ErrorCode.DELETE_QUESTION_ERROR,"问题删除失败");
        }
    }

    @Override
    public APIResponse createQuestion(Integer type, Integer score, Integer categoryId, JSONObject content) {
        Question question = new Question();
        question.setUserId(SecurityUtil.getUserId());
        question.setCategoryId(categoryId);
        question.setType(type);
        question.setScore(score);
        question.setImage((String) content.remove("image"));
        question.setContent(JSONObject.toJSONString(content.get("content")));
        try{
            testService.generateQuestions(Arrays.asList(question));
        } catch (Exception e) {
            return APIResponse.error("题目内容有问题");
        }
        int insert = questionMapper.insert(question);
        if(insert <= 0) {
            return APIResponse.error("新增问题失败");
        }
        return APIResponse.success(question.getQuestionId());
    }

    @Override
    public APIResponse updateQuestion(Question question) {
        synchronized (SecurityUtil.getUserId()) {
            Question question1 = questionMapper.selectById(question.getQuestionId());
            if(Objects.isNull(question1)) {
                return APIResponse.error("无该题目!");
            }
            //检查用户权限
            SecurityUtil.checkUserAuthority(question1.getUserId());
            question.setQuestionId(question1.getQuestionId());
            question.setUserId(question1.getUserId());
            //修改题目内容
            if(!Objects.isNull(question.getContent())) {
                try {
                    testService.generateQuestions(Arrays.asList(question));
                } catch (Exception e) {
                    return APIResponse.error("题目内容有问题");
                }
            }
            //修改题目分类
            if(!Objects.isNull(question.getCategoryId())) {
                Category category = categoryMapper.selectById(question.getCategoryId());
                if (Objects.isNull(category)) {
                    return APIResponse.error("新题目分类有问题");
                }
                SecurityUtil.checkUserAuthority(category.getUserId());
            }
            questionMapper.updateById(question);
            return APIResponse.success("更新成功");
        }
    }

    @Override
    public APIResponse getQuestionsByUserId() {
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        try {
            wrapper.eq("user_id",SecurityUtil.getUserId());
            List<Question> questions = questionMapper.selectList(wrapper);
            return APIResponse.success(questions);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public APIResponse getQuestionsByCategoryId(Integer categoryId) {
        if(Objects.isNull(categoryId)) {
            return APIResponse.error("分类id不能为空！");
        }
        try {
            return APIResponse.success(questionMapper.getQuestionsByCategoryId(categoryId,SecurityUtil.getUserId()));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public APIResponse updateCategoryOfQuestion(Integer questionId, Integer newCategoryId) {
        synchronized (questionId) {
                Question question = questionMapper.selectById(questionId);
                Category category = categoryMapper.selectById(newCategoryId);
                //判断是否为空
                if (Objects.isNull(question)) {
                    return APIResponse.error(ErrorCode.NULL_DATA_ERROR, "无此问题");
                }
                if (Objects.isNull(category)) {
                    return APIResponse.error(ErrorCode.NULL_DATA_ERROR, "无此分类");
                }
                //判断用户权限
                SecurityUtil.checkUserAuthority(question.getUserId());
                SecurityUtil.checkUserAuthority(category.getUserId());
                question.setCategoryId(newCategoryId);
                questionMapper.updateById(question);
                return APIResponse.success("修改成功");
        }
    }

    @Override
    public APIResponse updateQuestion(Integer id, JSONObject content) {
        synchronized (SecurityUtil.getUserId()) {
            try {
                Question question = questionMapper.selectById(id);
                //判断用户权限
                SecurityUtil.checkUserAuthority(question.getUserId());
                if (Objects.isNull(content)) {
                    return APIResponse.error(ErrorCode.NULL_DATA_ERROR, "content不能为空");
                }
                question.setContent(content.toJSONString());
                testService.generateQuestions(Arrays.asList(question));
                questionMapper.updateById(question);
                return APIResponse.success("更新内容成功");
            } catch (Exception e) {
                e.printStackTrace();
                return APIResponse.error("问题更新失败");
            }
        }
    }

    @Override
    public APIResponse getQuestionsByTestId(Long id) {
        List<QuestionTest> questionTests = questionTestMapper.selectList(new QueryWrapper<QuestionTest>().eq("test_id", id));
        if(Objects.isNull(questionTests) || questionTests.isEmpty()) {
            return APIResponse.error(ErrorCode.NULL_DATA_ERROR,"无此测试或该测试没有题目");
        }
        QueryWrapper<Question> wrapper = new QueryWrapper<>();
        List<Long> ids = new ArrayList<>();
        for (QuestionTest questionTest : questionTests) {
            ids.add(questionTest.getQuestionId());
        }
        wrapper.in("question_id", ids);
        List<Question> questions = questionMapper.selectList(wrapper);
        return APIResponse.success(questions);
    }

}
